#pragma once

#include <iostream>
#include <string>
#include <fstream>
#include <unordered_map>
#include "Log.hpp"

using namespace log_ns;

static const std::string sep = ": ";
class Dict
{
private:
    void LoadDict()
    {
        // 打开文件
        std::ifstream in(_dict_path);
        if (!in.is_open())
        {
            LOG(FATAL, "open %s error\n", _dict_path.c_str());
            exit(1);
        }

        std::string line;
        while(std::getline(in, line))
        {
            LOG(DEBUG, "load line: %s sucess\n", line.c_str());

            if (line.empty()) continue; // 跳过空行

            size_t pos = line.find(sep);
            if (pos == std::string::npos) continue; // 这一行并没有分隔符

            // 取下 key
            std::string key = line.substr(0, pos);
            if (key.empty()) continue; // 取 key 失败

            // 取下 val
            std::string val = line.substr(pos + sep.size());
            if (val.empty()) continue; // 取 val 失败

            _dict[key] = val;
        }

        LOG(DEBUG, "load dict: %s sucess\n", _dict_path.c_str());
        in.close();
    }
public:
    Dict(const std::string& path) : _dict_path(path)
    {
        LoadDict(); // 加载字典
    }
    
    std::string Translate(const std::string key)
    {
        if (key.empty()) return "None";

        if (_dict.count(key))
            return _dict[key];
        else
            return "None";
    }
    ~Dict()
    {}
private:
    std::unordered_map<std::string, std::string> _dict; // 存储字典数据
    std::string _dict_path; // 从哪里读取数据
};